package hystrix;

import com.netflix.hystrix.HystrixCollapser;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import feign.Feign;
import feign.gson.GsonDecoder;
import feign.gson.GsonEncoder;
import rest.entity.User;
import rest.feign.SpringbootClient;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

public class CollapserUserCommand extends HystrixCommand<Map<String, User>> {
   //单独调用的collection集合，第一个参数类型User为返回对象，第二个参数类型为传入参数，详情参考SingleUserCommand的继承
    Collection<HystrixCollapser.CollapsedRequest<User, String>> map;
    List<String> userIdList;
    String url;

    protected CollapserUserCommand(Collection<HystrixCollapser.CollapsedRequest<User, String>> map, String url) {
        super(Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey("CollapserUserCommand")));
        this.map = map;
        this.url = url;
    }

    /**
     * Implement this method with code to be executed when {@link #execute()} or {@link #queue()} are invoked.
     *
     * @return R response type
     * @throws Exception if command execution fails
     */
    protected Map<String, User> run() throws Exception {
        SpringbootClient springbootClient = Feign.builder().
                decoder(new GsonDecoder()). //解码器，将json转化为对象
//                encoder(new GsonEncoder()). //编码器，将对象转化为json
                target(SpringbootClient.class, url);
        System.out.println("***********有人触发了合并查询***********");
        userIdList = new ArrayList<String>();
        for (HystrixCollapser.CollapsedRequest<User, String> collapsedRequest : map) {
            userIdList.add(collapsedRequest.getArgument());
        }
        StringBuilder sb = new StringBuilder();
        for (String s : userIdList) {
            sb.append(s).append(",");
        }
        sb.toString();
        Map<String, User> users = springbootClient.getUsers(sb.toString());
        return users;
    }
}
